<template>
  <div class="rule-container">
    <div class="create-container">
      <el-button type="primary" @click="open">增加停车计费规则</el-button>
      <el-button @click="exportToExcel">导出Excel</el-button>
    </div>
    <!-- 表格区域 -->
    <div class="table">
      <el-table :data="ruleList" style="width: 100%">
        <el-table-column type="index" label="序号" />
        <el-table-column label="计费规则编号" prop="ruleNumber" />
        <el-table-column label="计费规则名称" prop="ruleName" />
        <el-table-column label="免费时长(分钟)" prop="freeDuration" />
        <el-table-column label="收费上线(元)" prop="chargeCeiling" />
        <el-table-column label="计费方式" :formatter="fn" prop="chargeType">
          <!-- <template #default="scope">
            {{ scope.row.chargeType }}
          </template> -->
        </el-table-column>
        <el-table-column label="计费规则" prop="ruleNameView" />
        <el-table-column label="操作" fixed="right" width="120">
          <template #default="scope">
            <el-button size="mini" type="text" @click="editCarruleList(scope.row.id)">编辑</el-button>
            <el-button size="mini" type="text" @click="delCarruleList(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div class="box">
      <!-- 分页器 -->
      <el-pagination :current-page="params.page" :page-sizes="[2, 4, 6, 8, 10]" :page-size="params.pageSize"
        layout="total,prev,pager,next,sizes" :total="total" @size-change="handleSizeChange"
        @current-change="handlecurrentChange" />
    </div>

    <!-- 弹窗 -->
    <el-dialog :visible="dialogVisible" @close="handleClose" width="580px"  top="2vh" :title="addForm.id ? '编辑规则' : '新增规则'">
      <!-- 表单接口 -->
      <div style="display: flex; justify-content: center;">
        <el-form ref="addForm" :model="addForm" :rules="addFormRules" label-position="top">
          <el-form-item label="计费规则编号" prop="ruleNumber">
            <el-input v-model="addForm.ruleNumber" />
          </el-form-item>
          <el-form-item label="计费规则名称" prop="ruleName">
            <el-input v-model="addForm.ruleName" />
          </el-form-item>

          <el-form-item label="计费方式" prop="chargeType">
            <el-radio-group v-model="addForm.chargeType" size="small">
              <el-radio label="duration" border>时长收费</el-radio>
              <el-radio label="turn" border>按次收费</el-radio>
              <el-radio label="partition" border>分段收费</el-radio>
            </el-radio-group>
          </el-form-item>

            <el-form-item label="免费时长">
              <div style="display: flex;justify-content: left;" width="100%">
                <el-input v-model="addForm.freeDuration" style="margin-top: 10px;"/>
                <p style="float: right; width: 60px; text-align: center;height: 20px;line-height: 40px;">分钟</p>
              </div>
              
            </el-form-item>
            <el-form-item label="收费上限">
              <div style="display: flex;justify-content: left;" width="100%">
                <el-input v-model="addForm.chargeCeiling" style="margin-top: 10px;"/>
                <p style="float: right; width: 60px; text-align: center;height: 20px;line-height: 40px;">元</p>
              </div>
              
            </el-form-item>
        

          <el-form-item label="计费规则">
            <!-- 按时长收费区域 -->
            <div v-if="addForm.chargeType === 'duration'" class="duration">每
              <el-input-number v-model="addForm.durationTime" controls-position="right" class="duration1" :min="1" />
              <el-form-item class="duration2">
                <el-select v-model="addForm.durationType">
                  <el-option label="分钟" value="minute" />
                  <el-option label="小时" value="hour" />
                </el-select>
              </el-form-item>
              <el-input v-model="addForm.durationPrice" class="duration3" />元
            </div>
            <!-- 按次收费区域 -->
            <div v-if="addForm.chargeType === 'turn'" class="turn">
              每次 <el-input v-model="addForm.turnPrice" class="turn1" /> 元
            </div>
            <!-- 按分段收费区域 -->
            <div v-if="addForm.chargeType === 'partition'" class="partition">
              <div class="item1"><el-input-number :min="1" v-model="addForm.partitionFrameTime" controls-position="right"
                  class="item11" style="width: 18%"></el-input-number>小时内,每小时收费<el-input
                  v-model="addForm.partitionFramePrice" class="item12" width="20%" /> 元</div>

              <div class="item2">每增加<el-input-number :min="1" v-model="addForm.partitionIncreaseTime"
                  controls-position="right" class="item21" style="width: 18%" />小时,增加<el-input
                  v-model="addForm.partitionIncreasePrice" class="item22" /> 元</div>
            </div>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <el-button size="mini" @click="def">取 消</el-button>
        <el-button size="mini" type="primary" @click="submit">确 定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { getCarruleListAPI, addCarruleListAPI, delCarruleListAPI, editCarruleListAPI, getCarruleListDetailAPI } from '@/api/rule'
import { utils, writeFileXLSX } from 'xlsx'
export default {
  name: 'Building',
  data() {
    return {
      ruleList: [],
      params: {
        page: 1,
        pageSize: 10
      },
      total: 0,
      dialogVisible: false,
      addForm: {
        ruleNumber: null, // 计费规则编号
        ruleName: null, // 计费规则名称
        chargeType: '', // 计费规则类型
        chargeCeiling: null, //上限

        freeDuration: null,// 免费时长

        durationTime: null, // 时长计费单位时间
        durationPrice: null, // 时长计费单位价格
        durationType: '',//时长收费种类

        turnPrice: null,// 按次收费每次价格

        partitionFrameTime: null, // 段内时间
        partitionFramePrice: null, // 段内费用
        partitionIncreaseTime: null, // 超出时间
        partitionIncreasePrice: null,// 超出费为收费价钱
      },
      addFormRules: {
        ruleNumber: [
          {
            required: true,
            message: '请输入规则编号',
            trigger: 'blur'
          }
        ],
        ruleName: [
          {
            required: true,
            message: '请输入规则名称',
            trigger: 'blur'
          }
        ],
        chargeType: [
          {
            required: true,
            message: '请选择收费类型',
            trigger: 'change'
          }
        ]
      }
    }
  },
  methods: {
    def() {
      this.dialogVisible = false
      this.clear()
    },
    // 导出excel
    async exportToExcel() {
      // 获取要导出的业务数据
      const res = await getCarruleListAPI(this.params)
      // 表头英文字段key
      const tableHeaderKeys = ['ruleNumber', 'ruleName', 'freeDuration', 'chargeCeiling', 'chargeType', 'ruleNameView']
      // 表头中文字段value
      const tableHeaderValues = ['计费规则编号', '计费规则名称', '免费时长(分钟)', '收费上线(元)', '计费方式', '计费规则']
      // 以excel表格的顺序调整后端数据
      const sheetData = res.data.rows.map((item) => {
        const obj = {}
        tableHeaderKeys.forEach(key => {
          obj[key] = item[key]
        })
        return obj
      })
      // 创建一个工作表
      const worksheet = utils.json_to_sheet(sheetData)
      // 创建一个新的工作簿
      const workbook = utils.book_new()
      // 把工作表添加到工作簿
      utils.book_append_sheet(workbook, worksheet, 'Data')
      // 改写表头
      utils.sheet_add_aoa(worksheet, [tableHeaderValues], { origin: 'A1' })
      writeFileXLSX(workbook, 'shixun1.xlsx')
    },
     editCarruleList(id) {
      this.dialogVisible = true
      getCarruleListDetailAPI(id).then((res) => {
        if (res.data.chargeType === 'duration') {
          const { id, ruleNumber, ruleName, freeDuration, chargeCeiling, chargeType,
             durationTime, durationPrice, durationType } = res.data
          this.addForm = { id, ruleNumber, ruleName, freeDuration, chargeCeiling, chargeType, 
            durationTime, durationPrice, durationType }
        } else if (res.data.chargeType === 'turn') {
          const { id, ruleNumber, ruleName, freeDuration, chargeCeiling, chargeType, 
            turnPrice } = res.data
          this.addForm = { id, ruleNumber, ruleName, freeDuration, chargeCeiling, chargeType, 
            turnPrice }
        } else {
          const { id, ruleNumber, ruleName, freeDuration, chargeCeiling, chargeType, 
            partitionFrameTime, partitionFramePrice, partitionIncreaseTime, partitionIncreasePrice } = res.data
          this.addForm = { id, ruleNumber, ruleName, freeDuration, chargeCeiling, chargeType, 
            partitionFrameTime, partitionFramePrice, partitionIncreaseTime, partitionIncreasePrice }
        }

      })
    },

    delCarruleList(id) {
      this.$confirm('是否确认删除当前计费规则？', { type: 'warning' }).then(() => {
        delCarruleListAPI(id).then(() => {
          this.$message.success('删除成功')
          this.getCarruleList()
        })
      })
    },
    clear() {
      this.addForm = {
        ruleNumber: null, // 计费规则编号
        ruleName: null, // 计费规则名称
        chargeType: '', // 计费规则类型
        chargeCeiling: null, //上限

        freeDuration: null,// 免费时长

        durationTime: null, // 时长计费单位时间
        durationPrice: null, // 时长计费单位价格
        durationType: '',//时长收费种类

        turnPrice: null,// 按次收费每次价格

        partitionFrameTime: null, // 段内时间
        partitionFramePrice: null, // 段内费用
        partitionIncreaseTime: null, // 超出时间
        partitionIncreasePrice: null // 超出费为收费价钱
      }
    },
    submit() {
      this.$refs.addForm.validate((ok) => {
        if (ok) {
          if (this.addForm.id) {
            editCarruleListAPI(this.addForm).then((res) => {
              this.$message.success('编辑成功')
              this.getCarruleList()
              this.dialogVisible = false
              this.clear()
            })
          } else {
            addCarruleListAPI(this.addForm).then(() => {
              this.$message.success('添加成功')
              this.getCarruleList()
              this.dialogVisible = false
              this.clear()
            })
          }
        }
      })
    },
    fn(row) {
      if (row.chargeType === 'duration') {
        return '时长收费'
      } else if (row.chargeType === 'turn') {
        return '按次收费'
      } else {
        return '分段收费'
      }
    },
    handleClose() {
      this.dialogVisible = false
      this.clear()
    },
    open() {
      this.dialogVisible = true
    },
    handlecurrentChange(page) {
      this.params.page = page
      this.getCarruleList()
    },
    handleSizeChange(pageSize) {
      this.params.pageSize = pageSize
      this.getCarruleList()
    },
    getCarruleList() {
      getCarruleListAPI(this.params).then((res) => {
        this.ruleList = res.data.rows
        this.total = res.data.total
      })
    }
  },
  mounted() {
    this.getCarruleList()
  }
}
</script>

<style lang="scss" scoped>
.item1 {

  .item11 {
    width: 100px;
  }

  .item12 {
    width: 250px
  }
}

.item2 {
  margin-top: 15px;

  .item21 {
    width: 100px;
  }

  .item22 {
    width: 250px
  }
}

.turn {
  .turn1 {
    width: 400px;
  }
}

.duration {
  display: flex;

  .duration1 {
    width: 80px;
  }

  .duration2 {
    width: 100px;
  }

  .duration3 {
    width: 250px;
  }
}

.item {
  display: inline-block;
}

.box {
  // 浮动
  // flex 弹性容器布局（快速实现子元素横向布局）
  display: flex;
  // 默认是从左往右 从右往坐
  justify-content: flex-end;
  // float: right;
}

.rule-container {
  padding: 20px;
  background-color: #fff;
}

.search-container {
  display: flex;
  align-items: center;
  border-bottom: 1px solid rgb(237, 237, 237, .9);
  padding-bottom: 20px;

  .search-label {
    width: 100px;
  }

  .search-main {
    width: 220px;
    margin-right: 10px;
  }
}

.create-container {
  margin: 10px 0px;
}

.page-container {
  padding: 4px 0px;
  text-align: right;
}

.form-container {
  padding: 0px 80px;
}</style>